package net.xdclass.listener;

import com.rabbitmq.client.AMQP;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import net.xdclass.enums.PayOrderType;
import net.xdclass.model.message.PayOrderStatusEventMessage;
import net.xdclass.service.WxPayService;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * @author Administrator
 * @description 检查 订单的支付状态
 * @since 2023-07-02 21:55
 */
@Component
@RabbitListener(queuesToDeclare = {@Queue("pay.order.status.dead.queue")})
@Slf4j
public class PayOrderStatusCheckListener {

    @Autowired
    WxPayService wxPayService;

    @RabbitHandler
    public void orderStatusHandler(PayOrderStatusEventMessage eventMessage,Message message, Channel channel) {

        Long orderId = eventMessage.getOrderId();
        String mchid = eventMessage.getMchid();
        String outTradeNo = eventMessage.getOutTradeNo();
        String status = wxPayService.queryOrderStatusByOutTradeNo(outTradeNo, mchid);
        if (PayOrderType.FINISH.name().equalsIgnoreCase(status)) {
            log.info("延迟消息: 订单交易完成");
        } else if (PayOrderType.PREPARE.name().equalsIgnoreCase(status)) {
            // 修改订单状态
            Boolean aBoolean = wxPayService.changeOrderStatusByOrderId(orderId, PayOrderType.PREPARE, PayOrderType.TIMEOUT);
            if (aBoolean) {
                log.info("订单超时，修改订单状态成功");
            } else {
                log.error("订单超时，修改订单状态失败");
                throw new RuntimeException("订单状态修改失败");
            }
        }

    }
}
